﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace KoSoft
{
	public class UtilImg
	{
		public static MemoryStream ImgCrop(string imgUrl, int finalWidth, int finalHeight)
		{
			Image img = Image.FromFile(imgUrl);

			int srcWidth = img.Width;
			int srcHeight = img.Height;
			int pointX = 0;
			int pointY = 0;
			int cutWidth = 0;
			int cutHeight = 0;
			double scale = finalWidth * 1.0 / finalHeight;
			if (srcWidth / srcHeight >= scale)
			{
				pointX = (int)((srcWidth - scale * srcHeight) / 2);
				cutWidth = (int)(scale * srcHeight);
				cutHeight = srcHeight;
			}
			else
			{
				pointY = (int)((srcHeight - srcWidth / scale) / 2);
				cutWidth = srcWidth;
				cutHeight = (int)(srcWidth / scale);
			}

			if (finalWidth == 0 && finalHeight != 0)
			{

			}

			Bitmap bmp = new Bitmap(finalWidth, finalHeight, PixelFormat.Format24bppRgb);
			Graphics graph = Graphics.FromImage(bmp);
			graph.Clear(Color.White);
			graph.DrawImage(
				img,//要绘制的 System.Drawing.Image。
				new Rectangle(0, 0, finalWidth, finalHeight),//System.Drawing.Rectangle 结构，它指定所绘制图像的位置和大小。将图像进行缩放以适合该矩形。
				pointX,//要绘制的源图像部分的左上角的 x 坐标。
				pointY,//要绘制的源图像部分的左上角的 y 坐标。
				cutWidth,//要绘制的源图像部分的宽度。
				cutHeight,//要绘制的源图像部分的高度。
				GraphicsUnit.Pixel//System.Drawing.GraphicsUnit 枚举的成员，它指定用于确定源矩形的度量单位。
			);
			MemoryStream ms = new MemoryStream();
			bmp.Save(ms, ImageFormat.Jpeg);

			img.Dispose();
			graph.Dispose();
			bmp.Dispose();
			return ms;
		}
	}
}
